let domain = !!window.location.href.match(
  /((?:\w+\.){1}(?:cn|top|com\.cn|com\.tw|com))/,
)
  ? window.location.href.match(
      /((?:\w+\.){1}(?:cn|top|com\.cn|com\.tw|com))/,
    )[1]
  : null;
let COOKIE_EXPIRES_DAYS = 30;

export function setCookie(name, value) {
  var exp = new Date();
  exp.setTime(exp.getTime() + COOKIE_EXPIRES_DAYS * 24 * 60 * 60 * 1000);

  // document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString() + ";path=/;domain=" + location.href.match(/((?:\w+\.){1}(?:cn|top|com\.cn|com\.tw|com))/)[1];
  let cookie =
    name + '=' + escape(value) + ';expires=' + exp.toGMTString() + ';path=/;';
  if (name === 'UserKey' || name === 'UserNameKey' || name === 'UserPhoneKey') {
    cookie = cookie + (domain ? 'domain=' + domain + ';' : ';');
    document.cookie = cookie;
  } else {
    document.cookie = cookie;
  }
  // location.hostname;
}

export function getCookie(c_name) {
  if (document.cookie.length > 0) {
    const cookie = unescape(document.cookie).replace(/ /g, '');

    var c_start = cookie.indexOf(c_name + '=');
    if (c_start !== -1) {
      c_start = c_start + c_name.length + 1;
      var c_end = cookie.indexOf(';', c_start);
      if (c_end === -1) c_end = cookie.length;
      let res = cookie.substring(c_start, c_end);

      return res === 'undefined' ? null : res;
    }
  }
  return null;
}

export function delCookie(name) {
  var exp = new Date();
  exp.setTime(exp.getTime() - 1);
  var cval = getCookie(name);
  if (cval !== null) {
    let cookie =
      name + '=' + cval + ';expires=' + exp.toGMTString() + ';path=/;';
    if (
      name === 'UserKey' ||
      name === 'UserNameKey' ||
      name === 'UserPhoneKey'
    ) {
      cookie = cookie + (domain ? 'domain=' + domain + ';' : ';');
    }
    document.cookie = cookie;
  }
}
